//
//  HomeVC.swift
//  LeTu
//
//  Created by gy on 2023/11/24.
//

import UIKit

class HomeVC: BaseViewController {
    
    private let flowlayout = WaterfallMutiSectionFlowLayout()
    private var viewModel = HomeVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        refreshData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(checkUpgrade), name: NSNotification.Name("HomeCheckUpgradeNotification"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadHomeDataNotification), name: Notification.Name("ReloadHomeDataNotification"), object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        refreshUI()
    }
    
    @objc private func checkUpgrade() {
        UserManager.checkUpgrade()
    }
    
    // MARK: - getData
    override func refreshData() {
        super.refreshData()
        
        refreshUI()
        getData(isLoad: false)
    }
    private func refreshUI() {
        navbar.updateInfo(keyword: viewModel.city)
        navbar.layoutSubviews()
    }
    @objc private func reloadHomeDataNotification() {
        guard viewModel.sourceArr.count == 0 else { return }
        getData(isLoad: false)
    }
    func getData(isLoad: Bool) {
        
        if isLoad == false {
            getBanner()
            scenicCollectionView.footerResetNoMoreData()
        }
        
        viewModel.getScenics(isLoad: isLoad) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            
            DispatchQueue.main.async {
                
                if isLoad {
                    strongSelf.scenicCollectionView.footerEndRefreshing()
                } else {
                    strongSelf.scenicCollectionView.headerEndRefreshing()
                }
                
                if dialog.code != 200 {
                    strongSelf.showMessage(message: dialog.message)
                }
                
                if strongSelf.viewModel.sourceArr.count == 0 || strongSelf.viewModel.sourceArr.count % strongSelf.viewModel.pageSize > 0 {
                    strongSelf.scenicCollectionView.footerEndRefreshingWithNoMoreData()
                }
                UIView.performWithoutAnimation {
                    strongSelf.scenicCollectionView.reloadData()
                }
                
            }
            
        }
        
    }
    func getBanner() {
        
        viewModel.getBanner { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            
            DispatchQueue.main.async {
                
                if dialog.code == 200 {
                    UIView.performWithoutAnimation {
                        strongSelf.scenicCollectionView.reloadData()
                    }
                }
                
            }

        }
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        view.addSubview(navbar)
        view.addSubview(scenicCollectionView)
        
        navbar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        scenicCollectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(navbar.snp.bottom)
        }
        
        flowlayout.delegate = self
        scenicCollectionView.delegate = self
        scenicCollectionView.dataSource = self
        scenicCollectionView.register(cellClass: HomeBannerCollectionViewCell.self)
        scenicCollectionView.register(cellClass: CollectItemCollectionViewCell.self)
        scenicCollectionView.register(cellClass: BaseEmptyCollectionViewCell.self)
        scenicCollectionView.register(headerClass: HomeClassifyCollectionReusableView.self)
        scenicCollectionView.register(headerClass: BaseEmptyHeaderCollectionReusableView.self)
        scenicCollectionView.register(footerClass: BaseEmptyFooterCollectionReusableView.self)
        scenicCollectionView.addRefreshHeaderCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: false)
        }
        scenicCollectionView.addRefreshFooterCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: true)
        }
        
        navbar.addressHandle = { [weak self] in
            guard let strongSelf = self else { return }
            let searchVC = SearchScenicVC()
            searchVC.selectCity = { [weak self] city, countryType in
                guard let strongSelf = self else { return }
                strongSelf.viewModel.countryType = countryType
                strongSelf.viewModel.city = city
                strongSelf.navbar.setAddress(city)
                strongSelf.scenicCollectionView.contentOffset = .zero
                strongSelf.getData(isLoad: false)
            }
            strongSelf.show(searchVC, sender: nil)
        }
        navbar.languageHandle = {
            LanguageManager.shared.exchangeLanguage()
        }
        navbar.textFieldWillBeiginHandle = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.show(SearchResultVC(keyword: ""), sender: nil)
        }
        
    }
    private lazy var navbar = HomeNavBar()
    private lazy var scenicCollectionView : UICollectionView = {
        let scenicCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowlayout)
        scenicCollectionView.backgroundColor = .app_white
        scenicCollectionView.showsVerticalScrollIndicator = false
        return scenicCollectionView
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension HomeVC: TransferEventReceivable {
    
    enum TransferEvent: TransferEventType {
        case clickClassify(Int)
        case clickScenic(ScenicModel)
    }
    
    func receive(event: TransferEventType) {
        
        switch event {
        case HomeVC.TransferEvent.clickClassify(let item):
            viewModel.currentClassifysIndex = item
            getData(isLoad: false)
        case HomeVC.TransferEvent.clickScenic(let scenicModel):
            toScenicDetail(scenicDetail: scenicModel)
        default:
            break
        }
        
    }
    func toScenicDetail(scenicDetail: ScenicModel) {
        show(ScenicDetailVC(scenicModel: scenicDetail), sender: nil)
    }
    
}

extension HomeVC: WaterfallMutiSectionDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            if indexPath.section == 0 {
                let header = collectionView.dequeueReusableViewHeader(BaseEmptyHeaderCollectionReusableView.self, indexPath: indexPath)
                header.backgroundColor = .app_viewBackgroundColor
                return header
            }
            let header = collectionView.dequeueReusableViewHeader(HomeClassifyCollectionReusableView.self, indexPath: indexPath)
            header.setClassifys(viewModel.classifys)
            return header
        } else {
            let footer = collectionView.dequeueReusableViewFooter(BaseEmptyFooterCollectionReusableView.self, indexPath: indexPath)
            return footer
        }
    }
    func insetForSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 12, left: 10, bottom: 0, right: 10)
    }
    func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize(width: screenWidth, height: section == 0 ? 0.01:HomeClassifyCollectionReusableView.getReusableViewHeight())
    }
    func referenceSizeForFooter(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize(width: screenWidth, height: 0.01)
    }
    func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        return 10
    }
    func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        return 10
    }
    func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int {
        switch section {
        case 1:
            return viewModel.sourceArr.count == 0 ? 1:2
        default:
            return 1
        }
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        
        switch indexPath.section {
        case 0:
            return HomeBannerCollectionViewCell.getCellHeight()
        case 1:
            if viewModel.sourceArr.count == 0 {
                return 160
            } else {
                let scenicModel = viewModel.sourceArr[indexPath.row]
                var cellHeight = CollectItemCollectionViewCell.getFixCellHeight()
                let itemW = (screenWidth-20-10)/2
                if let url = URL.encodedURL(string: scenicModel.picUrl) {
                    cellHeight += XHWebImageAutoSize.imageHeight(for: url, layoutWidth: itemW, estimateHeight: itemW)
                }
                return cellHeight
            }
        default:
            return 0.01
        }
                
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return viewModel.sourceArr.count == 0 ? 1:viewModel.sourceArr.count
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(HomeBannerCollectionViewCell.self, indexPath: indexPath)
            cell.setBanners(viewModel.banners)
            return cell
        }
        
        if viewModel.sourceArr.count == 0 {
            let cell = collectionView.dequeueReusableCell(BaseEmptyCollectionViewCell.self, indexPath: indexPath)
            cell.setInfo(iconName: "", title: "内容持续更新中，敬请期待")
            return cell
        }
        let cell = collectionView.dequeueReusableCell(CollectItemCollectionViewCell.self, indexPath: indexPath)
        let collectModel = viewModel.sourceArr[indexPath.row]
        cell.setScenicModel(collectModel)
        cell.imgView.sd_setImage(with: URL.encodedURL(string: collectModel.picUrl)) { img, error, type, url in
            
            if let image = img, let url = url {
                
                XHWebImageAutoSize.storeImageSize(image, for: url) { [weak self] (result) in
                    
                    guard let strongSelf = self else { return }
                    XHWebImageAutoSize.reloadStateFromCache(for: url)
                    strongSelf.scenicCollectionView.xh_reloadData(for: url)
                    
                }
                
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard indexPath.section == 1, viewModel.sourceArr.count > 0 else { return }
        toScenicDetail(scenicDetail: viewModel.sourceArr[indexPath.row])
    }

}
